<!--
 * @Description: 需求大厅
 * @Author: Kerwin
 * @Date: 2024-09-04 17:21:25
 * @LastEditTime: 2025-02-24 11:50:05
 * @LastEditors:  Please set LastEditors
-->

<template>
    <view>
        <u-navbar :border-bottom="false" back-icon-color="#000"
            :background="{ 'background-color': isSticky ? '#fff' : 'transparent' }">
            <template v-slot>
                <view class="custom-navbar">
                    <view class="left" @click="toMyDemand">
                        <u-icon :name="icon_demand" size="48"></u-icon>
                        <view class="name">我的需求</view>
                        <u-icon name="arrow-up-fill" color="#666" size="20"
                            style="transform: rotate(90deg) translateX(0rpx);"></u-icon>
                    </view>
                    <view class="right" @click="toAdd">
                        <u-icon :name="icon_add" size="66"></u-icon>
                    </view>
                </view>
            </template>
        </u-navbar>
        <u-tabs name="cate_name" count="cate_count" :list="tabs" :is-scroll="false" v-model="current"
            :bg-color="isSticky ? '#fff' : 'transparent'" inactive-color="#666666" active-color="#1A1A1A" @change="change"
            :bar-style="{ 'background-color': '#FF6C18' }" :offset="[10, 20]"></u-tabs>
        <u-waterfall v-model="flowList" ref="uWaterfallRef">
            <template v-slot:left="{ leftList }">
                <view class="demo-warter" v-for="(item, index) in leftList" :key="index" @click="toDetail(item.id)">
                    <!-- 警告：微信小程序中需要hx2.8.11版本才支持在template中结合其他组件，比如下方的lazy-load组件 -->
                    <u-lazy-load threshold="-450" border-radius="10" :image="item.previewImage"
                        :index="index"></u-lazy-load>
                    <view @click.stop="tagOnClick" class="demo-title" v-html="wrapWordsWithSpan(item.name || item.content)"></view>
                    <view class="demo-tag">
                        <view class="demo-tag-text">
                            <text v-for="tag in item.tags" v-html="`${tag}`"></text>
                        </view>
                        <view class="demo-tag-views" v-if="item.favoriteCount">
                            <u-icon :name="icon_views" color="#666" size="40"></u-icon>
                            <text style="margin-left: 8rpx;">{{ item.favoriteCount }}</text>
                        </view>
                    </view>
                </view>
            </template>
            <template v-slot:right="{ rightList }">
                <view class="demo-warter" v-for="(item, index) in rightList" :key="index" @click="toDetail(item.id)">
                    <u-lazy-load threshold="-450" border-radius="10" :image="item.previewImage"
                        :index="index"></u-lazy-load>
                    <view class="demo-title" v-html="wrapWordsWithSpan(item.name || item.content)"></view>
                    <view class="demo-tag">
                        <view class="demo-tag-text">
                            <text v-for="tag in item.tags" v-html="`${tag}`"></text>
                        </view>
                        <view class="demo-tag-views" v-if="item.favoriteCount">
                            <u-icon :name="icon_views" color="#666" size="40"></u-icon>
                            <text style="margin-left: 8rpx;">{{ item.favoriteCount }}</text>
                        </view>
                    </view>
                </view>
            </template>
        </u-waterfall>
        <u-loadmore style="margin-top: 30rpx;" color="#ccc" :status="loadStatus" @loadmore="getData"></u-loadmore>
    </view>
</template>

<script lang="ts" setup>
import { onReachBottom, onLoad, onPageScroll } from '@dcloudio/uni-app';
import { reactive, ref } from 'vue';
import icon_add from "@/static/add.svg"
import icon_demand from "@/packageD/static/img/icon_demand.svg"
import icon_views from "@/packageD/static/img/views.svg"
import { route, timeDetia } from '@/utils/common';
import { socialApi } from '@/api';
import { getImgFullPath } from '@/utils';

const tabs = ref([{
    cate_name: '全部'
}, {
    cate_name: '餐饮'
}, {
    cate_name: '定制',
}])
const current = ref(0)
function change(index: any) {
    console.log("index", index);
}
interface Dynamic {
    id: number
    userId: number
    videoUrl: string
    contentType: number
    type: number
    content: string
    previewImage?: string
    tags?: string
    user: {
        nickname: string
        username: string
        avatar: string
    }
    createTime: number | string
    files: string[]
    location: any
}
const flowList = ref<Dynamic[]>([])
const uWaterfallRef = ref()
const loadStatus = ref('loading')

const pageData = reactive({
    pageSize: 10,
    pageIndex: 1,
    finished: false,
})
async function getData() {
    if (pageData.finished) return
    loadStatus.value = 'loading';
    const { data } = await socialApi.dynamicList({
        ...pageData,
        type: 4,
        detail: true
    })
    const { records, pages, current } = data
    const arr = formatData(records)
    flowList.value.push(...arr)
    if (current < pages) {
        pageData.pageIndex = current + 1
        loadStatus.value = 'loadmore';
    } else {
        pageData.finished = true
        loadStatus.value = 'nomore'
    }
}

function formatData(arr: Dynamic[]) {
    arr.forEach(item => {
        item.files = item.videoUrl.split(',').map(url => getImgFullPath(url) || '')
        item.previewImage && (item.previewImage = getImgFullPath(item.previewImage) || '')
        item.createTime = timeDetia(item.createTime as number * 1000)
        if (item.tags && typeof item.tags === 'string' && item.tags.startsWith('[') && item.tags.endsWith(']')) {
            item.tags && (item.tags = JSON.parse(item.tags))
        }
    })
    return arr
}

function remove(id: any) {
    uWaterfallRef.value.remove(id);
}
function clear() {
    uWaterfallRef.value.clear();
}
function toDetail(id: any) {
    route({
        url: '/packageD/pages/demand/detail',
        params: {
            id,
        },
    })
}
function toMyDemand() {
    route({
        url: '/packageD/pages/demand/mine',
    })
}

function toAdd() {
    route({
        url: '/packageA/pages/tweetEdit/index',
    })
}

function wrapWordsWithSpan(htmlContent: string) {
    // 正则表达式，匹配英文单词并忽略HTML标签内的内容
    const newStr = htmlContent.replace(/<span([^>]*)>/g, '<span$1 @click="tagOnClick($event)">');
    return newStr
}
function tagOnClick(event: { target: any; }) {
    console.log(event.target.nodeName );
    const span = event.target;
    // const param = span.getAttribute('data-param');
}

onLoad(() => {
    getData()
})
onReachBottom(async () => {
    try {
        await getData()
    } catch (error) {
        console.log(error)
    }
})
const isSticky = ref(false)
onPageScroll((e) => {
    const { scrollTop } = e
    isSticky.value = scrollTop > 44
})
const tabsStyleTop = ref('44px')
</script>

<style lang="scss" scoped>
@import '@/styles/helper.scss';

page {
    background: #f7f7f7;
}

.custom-navbar {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 24rpx;

    .left {
        display: flex;
        align-items: center;
        background: #FFF0E7;
        border-radius: 30rpx;
        padding-right: 10rpx;
        font-size: 24rpx;

        .name {
            margin: 0 12rpx;
        }
    }
}

:deep(.u-tabs) {
    position: sticky;
    top: 0;
    // #ifdef H5
    top: calc(v-bind(tabsStyleTop) + env(safe-area-inset-top));
    // #endif
    background: hsl(0, 0%, 100%);
    z-index: 2;
}

.demo-warter {
    border-radius: 8px;
    margin: 5px;
    background-color: #ffffff;
    padding: 8px;
    position: relative;
}

.u-close {
    position: absolute;
    top: 32rpx;
    right: 32rpx;
}

.demo-image {
    width: 100%;
    border-radius: 4px;
}

.demo-title {
    font-size: 30rpx;
    margin-top: 5px;
    color: $u-main-color;
    @include ellipsis(1);

    :deep(.fn-param) {
        color: rgb(84, 84, 222);
        font-size: 26rpx;
        margin: 0 4rpx;
        display: inline-block;
    }
}

.demo-tag {
    display: flex;
    margin-top: 16rpx;
    justify-content: space-between;
    align-items: center;
    color: #999999;

    .demo-tag-text {
        font-size: 24rpx;
    }

    .demo-tag-views {
        display: flex;
        align-items: center;
    }
}
</style>